<?php

namespace App\Http\Controllers\Platform\Setting;

use App\Models\Game\Config\Game;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Resources\Common\DataResource;
use App\Models\Game\Platform\Org\Config;

class ConfigController extends Controller
{

    /**
     * 获取数据
     */
    public function getData(Request $request)
    {
        $this->validate($request, [
            'plat_code' => 'required|string|max:64'
        ]);
        $platCode = $request->input('plat_code');

        $config = Config::where('plat_code', $platCode)->firstOrFail();

        $games = Game::whereJsonContains('private', $platCode)
            ->orWhereNull('private')
            ->pluck('code')
            ->toArray();

        $config['games'] = $games;

        return new DataResource($config);
    }

    /**
     * 更新或创建数据
     *
     * @param string $platCode
     */
    public function updateOrCreate(Request $request)
    {
        $this->validate($request, [
            'plat_code' => 'required|string|max:64',
            'currency' => 'required|array|between:1,100',
            'payment' => 'required|integer|in:1,2,3',
            'rate' => 'nullable|numeric|between:0.0001,1',
        ]);

        $config = Config::updateOrCreate($request->only([
            'plat_code'
        ]), $request->only([
            'payment', 'currency', 'rate'
        ]));

        // 通知游戏端配置修改
        $config->syncGameService();

        return new DataResource($config);
    }

    /**
     * 更新或创建数据【UI】
     */
    public function updateOrCreateByUi(Request $request)
    {
        $this->validate($request, [
            'plat_code' => 'required|string|max:64',
            'return_type' => 'required|integer|in:0,1,2',
            'return_url' => 'nullable|required_if:return_type,2|string|max:1024',
            'oem' => 'nullable|string|max:64',
            'more_game' => 'required|integer|in:1,2',
        ]);

        // 排除空字段
        $ui = collect($request->only([
            'return_type', 'return_url', 'oem', 'more_game'
        ]))->reject(function ($value) {
            return is_null($value);
        });

        $config = Config::updateOrCreate($request->only([
            'plat_code'
        ]), [
            'ui' => $ui->isEmpty() ? null : $ui->all()
        ]);

        // 通知游戏端配置修改
        $config->syncGameService();

        return new DataResource($config->ui);
    }

    /**
     * 更新或创建数据【接入游戏】
     */
    public function updateOrCreateByGames(Request $request)
    {
        $this->validate($request, [
            'plat_code' => 'required|string|max:64',
            'games' => 'nullable|array',
        ]);

        $games = $request->input('games');

        $config = Config::updateOrCreate($request->only([
            'plat_code'
        ]), [
            'games' => empty($games) ? null : $games
        ]);

        // 通知游戏端配置修改
        $config->syncGameService();

        return new DataResource($config->games);
    }
}
